package com.fenghongzhang.day007valueanim;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class RefreshLayout extends LinearLayout {

    LinearLayout linearLayout;
    LayoutParams layoutParams;

    PointF pointF = new PointF();
    public RefreshLayout(@NonNull Context context) {
        super(context);
    }

    public RefreshLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void init(){
         linearLayout = new LinearLayout(getContext());
         layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 200);

         layoutParams.topMargin = -200;
        linearLayout.setLayoutParams(layoutParams);
        linearLayout.setBackgroundColor(Color.RED);
        addView(linearLayout);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                pointF.x = event.getX();
                pointF.y = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
              layoutParams = (LayoutParams) linearLayout.getLayoutParams();
              layoutParams.topMargin += event.getY()- pointF.y;


              if(layoutParams.topMargin > 0){
                  layoutParams.topMargin = 0;
              }

              if(layoutParams.topMargin < -200){
                  layoutParams.topMargin = -200;
              }


              linearLayout.setLayoutParams(layoutParams);

                pointF.y = event.getY();
                pointF.x = event.getX();


                break;
            case MotionEvent.ACTION_UP:

                layoutParams = (LayoutParams) linearLayout.getLayoutParams();

                if(layoutParams.topMargin > -100){
                    startAnim(layoutParams.topMargin,0);
                }else{
                    startAnim(layoutParams.topMargin,-200);
                }

                break;
        }
        return true;

    }

    private void startAnim(int topMargin, int i) {
        ValueAnimator valueAnimator = ValueAnimator.ofInt(topMargin,i);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Integer animatedValue = (Integer) animation.getAnimatedValue();
                layoutParams = (LayoutParams) linearLayout.getLayoutParams();
                layoutParams.topMargin = animatedValue;
                linearLayout.setLayoutParams(layoutParams);

            }
        });

        valueAnimator.start();
    }
}
